<?php

namespace Utuo;

/**
 * 微信公众平台扩展库
 *
 * @author 雨中歌者
 */
class WechatExt {
	// 微信公众平台接口token
	private $token;
	// 微信公众平台登录账号
	private $username;
	// 微信公众平台登录密码
	private $password;
	// web token
	private $webToken;
	// cookie保存位置
	private $cookieFileName;
	// web token保存位置
	private $webTokenFileName;
	
	// result
	private $result;
	
	/**
	 * 构造函数
	 *
	 * @param string $token
	 * @param string $username
	 * @param string $password
	 */
	public function __construct($token, $username, $password) {
		$this->token = $token;
		$this->username = $username;
		$this->password = $password;
		$this->setCookieFileName($username);
		empty($this->webTokenFileName) or $this->webToken = file_get_contents($this->webTokenFileName);
	}
	
	/**
	 * 主动发送单条消息
	 * @param string $fakeId
	 * @param string $content
	 * @return number|boolean
	 */
	public function sendMessage($fakeId,$content){
		dump($this->webToken);
		if (file_exists($this->cookieFileName) || $this->login()=== true){
			$url = "https://mp.weixin.qq.com/cgi-bin/singlesend?t=ajax-response";
			$referer = "https://mp.weixin.qq.com/";
			$postFields = array(
				'tofakeid' => $fakeId,
					'type' => 1,
					'error' => 'false',
					'token' => $this->webToken,
					'content' => $content,
					'ajax' => 1
			);
			$response = $this->post($url, $postFields, $referer);
			$result = json_decode($response,true);
			dump($postFields);
			dump($result);
			if ($result['msg']=='ok'){
				return 1;
			} elseif ($result['ret']=='-2000') {
				return -1;
			} else {
				return 0;
			}
		} else {
			return false;
		}
	}
	
	/**
	 * 登录
	 *
	 * @return boolean
	 */
	public function login() {
		$url = "https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN";
		$referer = "https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN";
		$postFields['username'] = $this->username;
		$postFields['pwd'] = md5($this->password);
		$postFields['f'] = 'json';
		$response = $this->post($url, $postFields, $referer);
		$result = json_decode($response,true);
		dump($result);
		if ($result['base_resp']['err_msg']=="ok"){
			preg_match('/&token=([\d]+)/i', $result['redirect_url'],$match);
			file_put_contents($this->webTokenFileName, $match[1]);
			$this->webToken = $match[1];
			return true;
		} else {
			$this->result = $result;
		}
		unlink($this->cookieFileName);
		return false;
	}
	
	/**
	 * 设置cookie保存位置
	 * @param string $username
	 */
	private function setCookieFileName($username){
		$this->cookieFileName = sprintf("saekv://%s.txt",md5($username));
	}
	
	/**
	 * POST提交数据
	 * 
	 * @param string $url
	 * @param array $postFields
	 * @param string $referer
	 * @return mixed
	 */
	private function post($url, $postFields, $referer) {
		$ch = curl_init($url);
		$options = array (
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_HEADER => false,
				CURLOPT_FOLLOWLOCATION => true,
				CURLOPT_ENCODING => "",
				CURLOPT_USERAGENT => "",
				CURLOPT_AUTOREFERER => true,
				CURLOPT_CONNECTTIMEOUT => 120,
				CURLOPT_TIMEOUT => 120,
				CURLOPT_MAXREDIRS => 10,
				CURLOPT_POST => true,
				CURLOPT_POSTFIELDS => $postFields,
				CURLOPT_SSL_VERIFYHOST => 0,
				CURLOPT_SSL_VERIFYPEER => false,
				CURLOPT_COOKIEFILE => $this->cookieFileName,
				CURLOPT_COOKIEJAR => $this->cookieFileName,
				CURLOPT_REFERER => $referer 
		);
		curl_setopt_array($ch, $options);
		$result = curl_exec($ch);
		curl_close($ch);
		return $result;
	}
}